from dotenv import load_dotenv
import os
import requests  # http request

from bs4 import BeautifulSoup  # web scraping
# Send the mail
import smtplib
# email body
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# System date and time manipulation
import datetime

load_dotenv()

now = datetime.datetime.now()

# Email content placeholder
content = ''

# Extracting Hacker New Stories


def extract_news(url):
    print('Extracting Hacker News Stories...')
    cnt = ''
    cnt += '<b>HN Top Stories:</b>\n' + '<br>' + '-'*50 + '<br>'
    response = requests.get(url)
    content = response.content
    soup = BeautifulSoup(content, 'html.parser')
    for i, tag in enumerate(soup.find_all('td', attrs={'class': 'title', 'valign': ''})):
        cnt += ((str(i+1)+' :: '+tag.text+'\n' + '<br>')
                if tag.text != 'More' else '')
    return cnt


cnt = extract_news('https://news.ycombinator.com')
content += cnt
content += '<br>------<br>'
content += '<br><br>End of Message'


# Lets send the email

print('Composing email...')

# Update your email details

EMAIL_SERVER = 'smtp.163.com'
EMAIL_PORT = 25
EMAIL_FROM = '18620358128@163.com'
EMAIL_TO = 'walker5111@qq.com'
EMAIL_PASS = 'development73'

msg = MIMEMultipart()
msg['Subject'] = 'Top News Stories HN [Automated Email]' + \
    ' ' + str(now.day) + '-' + str(now.month)+'-' + str(now.year)
msg['From'] = EMAIL_FROM
msg['To'] = EMAIL_TO

msg.attach(MIMEText(content, 'html'))

print('Initiating Server ...')
server = smtplib.SMTP(EMAIL_SERVER, EMAIL_PORT)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(EMAIL_FROM, EMAIL_PASS)
server.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
print('Email Sent...')
server.quit()
